<?php
/**
 *
 * @user: leo
 * @date: 2021/6/30
 * @createTime: 15:22
 * @company: 迈酷网络科技 http://www.maicooit.com
 */
namespace app\admin\controller\user;

use app\BaseController;
use app\controller\Response;
use app\admin\logic\common\Auth as AuthLogic;
use app\admin\logic\user\Auth as UserAuthLogic;
use app\admin\logic\user\Menu as MenuLogic;
use app\admin\logic\user\UserData as UserDataLogic;
use app\admin\logic\user\User as UserLogic;

class Auth extends BaseController{
    /**
     * @OA\Post(
     *   path="/admin/auth/reg",
     *   tags={"用户验证相关接口"},
     *   summary=" 用户注册",
     *   @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="content-type/json",
     *         @OA\Schema(
     *           @OA\Property(description="租户", property="domain", type="string"),
     *           @OA\Property(description="用户名", property="user_name", type="string"),
     *           @OA\Property(description="密码", property="password", type="string"),
     *           required={"user_name","password"})
     *       )
     *     ),
     *   @OA\Response(
     *     response=200,
     *     description="A list with products"
     *   )
     * )
     */
    public function reg(){
        try{
            $Info = request()->post();
            $domain = $Info['domain'];
            $user_name = $Info['user_name'];
            $password = think_encrypt($Info['password']);
            //注册
            $reg_res = UserAuthLogic::UserRegLogic($domain,$user_name,$password);
            if($reg_res){
                $res = Response::succJson('',0,'注册成功！');
                return json($res);
            }else{
                $res = Response::errJson('',200,'注册失败！');
                return json($res);
            }
        }catch (\Exception $e){
            $res = Response::errJson('',$e->getCode(),$e->getMessage());
            return json($res);
        }
    }
    /**
     * @OA\Post(
     *   path="/admin/auth/login",
     *   tags={"用户验证相关接口"},
     *   summary=" 用户登录",
     *   security={
     *     {"basicAuth"={}}
     *   },
     *   @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="application/x-www-form-urlencoded",
     *         @OA\Schema(
     *           @OA\Property(description="租户", property="domain", type="string"),
     *           @OA\Property(description="用户名", property="user_name", type="string"),
     *           @OA\Property(description="密码", property="password", type="string"),
     *           @OA\Property(description="grant_type", property="grant_type", type="string",default="client_credentials"),
     *           required={"user_name","password"})
     *       )
     *     ),
     *   @OA\Response(
     *     response=200,
     *     description="A list with products"
     *   )
     * )
     */
    public function login(){
        try{
 
            $Info = request()->post();
            $domain = $Info['domain'];
            $user_name = $Info['user_name'];
            $password = think_encrypt($Info['password']);
 
            //校验账户登录权限
            $login_res = UserAuthLogic::UserLoginLogic($domain,$user_name,$password);
            $userInfo = "";

            //检查user_data表
            if($login_res){
                $UserData = UserDataLogic::UserDataFindByIdLogic($login_res['user_id']);
                if(!$UserData){
                    //初始化
                    $UserDataArr['user_id'] = $login_res['user_id'];
                    $UserDataArr['nickname']  = $login_res['user_name'];
                    $UserDataArr['score'] = 0;
                    $UserDataArr['login'] = 1;
                    $UserDataArr['reg_ip'] = get_real_ip();
                    $UserDataArr['reg_time'] = date('Y-m-d H:i:s');
                    $UserDataArr['last_login_ip'] = get_real_ip();
                    $UserDataArr['last_login_time'] = date('Y-m-d H:i:s');
                    UserDataLogic::UserDataAddLogic($UserDataArr);
                }else{
                    //更新
                    $UserDataArr['user_id'] = $login_res['user_id'];
                    $UserDataArr['nickname']  = $login_res['user_name'];
                    $UserDataArr['login'] = $UserData['login']+1;
                    $UserDataArr['last_login_ip'] = get_real_ip();
                    $UserDataArr['last_login_time'] = date('Y-m-d H:i:s');
                    UserDataLogic::UserSaveLogic($UserDataArr);
                }
            }

            if($login_res){
                
				$public_path = public_path();
                $publicKey  = file_get_contents($public_path.'cert/#@!$pubkey.pem');
                $privateKey = file_get_contents($public_path.'cert/#@!$privkey.pem');
                // create storage
                $storage = new \OAuth2\Storage\Memory(array(
                    'keys' => array(
                        'public_key'  => $publicKey,
                        'private_key' => $privateKey,
                    ),
                    // add a Client ID for testing
                    'client_credentials' => array(
                        '100' => array('client_secret' => '101')
                    ),
                ));
                $server = new \OAuth2\Server($storage, array(
                    'use_jwt_access_tokens' => true,
                ));

                $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage)); // minimum config
                $object =  $server->handleTokenRequest(\OAuth2\Request::createFromGlobals());

                $login_res['jwt'] = $object->parameters;

                //$rolesStr = "";
                if($login_res){
                    //获取用户拥有的角色
                    $roles = AuthLogic::getRolesForUserLogic($login_res['user_name'],$login_res['domain']);
                    $rolesStr = arr2str($roles);
                }
                $login_res['roles'] = $rolesStr;

                $res = Response::loginSuccJson($login_res,$userInfo,0,'登录成功！');
                return json($res);

            }else{
                $res = Response::errJson('',200,'登录失败！');
                return json($res);
            }
        }catch (\Exception $e){
            $res = Response::errJson('',$e->getCode(),$e->getMessage().',错误行数：'.$e->getLine());
            return json($res);
        }
    }
    /**
     * @OA\Get(
     *   path="/admin/auth/getMenu",
     *   tags={"用户验证相关接口"},
     *   summary="获取系统菜单",
     *   @OA\Parameter(name="domain", in="query", description="域", @OA\Schema(type="string")),
     *   @OA\Parameter(name="user_name", in="query", description="用户名", @OA\Schema(type="string")),
     *   @OA\Parameter(name="roles", in="query", description="角色", @OA\Schema(type="string")),
     *   @OA\Response(
     *     response=200,
     *     description="A list with products"
     *   )
     * )
     */
    public function getMenu(){
        try{
            $Info = request()->get();
            $domain = $Info['domain'];
            $user_name = $Info['user_name'];
            $roles = $Info['roles'];
            $policy = AuthLogic::getPermissionsForUserLogic($user_name,$roles,$domain); //菜单权限
            $menuAll = MenuLogic::MenuAllLogic($domain);
            $menuTree = list_to_tree($menuAll->toArray(),'menu_id','pid','children',1);
            $menu = getmenu($menuTree);
            if($menu){
                $res = Response::succJson($menu,0,'获取数据成功！');
                return json($res);
            }else{
                $res = Response::errJson('',200,'获取数据失败！');
                return json($res);
            }
        }catch (\Exception $e){
            $res = Response::errJson('',$e->getCode(),$e->getMessage().'，错误行号：'.$e->getLine());
            return json($res);
        }
    }
}